package com.hz.filemanager.ui.fragment;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.hz.filemanager.R;
import com.hz.filemanager.model.DialogManager;
import com.hz.filemanager.ui.MainActivity;
import com.hz.filemanager.ui.base.BaseActivity;
import com.hz.filemanager.ui.base.BaseFragment;
import com.hz.filemanager.ui.base.SelectableFragment;
import com.hz.filemanager.utils.FileUtils;
import com.kathline.library.Function;
import com.kathline.library.common.ZFileAdapter;
import com.kathline.library.common.ZFileViewHolder;
import com.kathline.library.content.ZFileBean;
import com.kathline.library.content.ZFileConfiguration;
import com.kathline.library.content.ZFileContent;
import com.kathline.library.content.ZFilePathBean;
import com.kathline.library.ui.adapter.ZFileListAdapter;
import com.kathline.library.util.ZFileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StorageFragment2 extends SelectableFragment implements View.OnClickListener {

    private RecyclerView zfileListPathRecyclerView;
    private SwipeRefreshLayout zfileListRefreshLayout;
    private RecyclerView zfileListListRecyclerView;
    private LinearLayout zfileListEmptyLayout;

    private boolean barShow = false;
    private ZFileAdapter<ZFilePathBean> filePathAdapter;
    private ZFileListAdapter fileListAdapter;

    private final String rootPath = ZFileContent.getSD_ROOT();// 根目录
    public static String nowPath;// 当前目录
    private OnBackPressedCallback callback;
    private LinearLayout modifyLl;
    private TextView renameTv;
    private TextView deleteTv;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_storage;
    }

    @Override
    protected void initView(View rootView) {
        zfileListPathRecyclerView = (RecyclerView) rootView.findViewById(R.id.zfile_list_pathRecyclerView);
        zfileListRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.zfile_list_refreshLayout);
        zfileListListRecyclerView = (RecyclerView) rootView.findViewById(R.id.zfile_list_listRecyclerView);
        zfileListEmptyLayout = rootView.findViewById(R.id.emptyLayout);

        modifyLl = rootView.findViewById(R.id.modify_ll);
        renameTv = rootView.findViewById(R.id.rename_tv);
        deleteTv = rootView.findViewById(R.id.delete_tv);
    }

    @Override
    protected void initEvent() {
        zfileListRefreshLayout.setEnabled(false);
        renameTv.setOnClickListener(this);
        deleteTv.setOnClickListener(this);


        nowPath = rootPath;

        initAll();
    }

    private void initAll() {
        ZFileContent.property(zfileListRefreshLayout, new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(nowPath);
            }
        });
        initPathRecyclerView();
        initListRecyclerView();
    }

    private void initPathRecyclerView() {
        filePathAdapter = new ZFileAdapter<ZFilePathBean>(getContext(), R.layout.item_file_path) {

            @Override
            protected void bindView(ZFileViewHolder holder, ZFilePathBean item, int position) {
                if (rootPath.equals(item.getFilePath()) || "Internal Storage".equals(item.getFileName()) || "root".equals(item.getFilePath())) {
                    holder.setText(R.id.item_zfile_path_title, "Internal Storage");
                } else {
                    holder.setText(R.id.item_zfile_path_title, item.getFileName());
                }
            }
        };
        //路径点击监听
        filePathAdapter.setOnClickListener(new ZFileAdapter.OnClickListener<ZFilePathBean>() {
            @Override
            public void onClick(View view, int position, ZFilePathBean data) {
                //选择模式下不允许点击路径
                if (fileListAdapter.isSelectModel()) return;
                //拿到当前路径数据
                final List<ZFilePathBean> datas = filePathAdapter.getDatas();
                //点击位置就是当前展示位置
                if (position == datas.size()) return;
                //只有根目录
                if (datas.size() == 1) return;

                //获取点击位置后的数据并移除
                if (filePathAdapter.removeAll(position + 1, datas.size())) {
                    //移除数据后立刻加载当前点击的目录数据
//                    if (datas.size() == 1) {//如果是根目录（根目录不是真实路径
//                        getData(ZFileContent.getSD_ROOT());
//                    } else {
//                        //其他目录则直接加载
                        getData(datas.get(datas.size() - 1).getFilePath());
//                    }
                } else {
                    Log.e("tip::", "data remove error");
                }
            }
        });

        zfileListPathRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        zfileListPathRecyclerView.setAdapter(filePathAdapter);

        ZFileConfiguration zFileConfig = ZFileContent.getZFileConfig();
        zFileConfig.setSortordBy(ZFileConfiguration.BY_NAME);//按名字排序
        zFileConfig.setSortord(ZFileConfiguration.ASC);//升序

        reservedFile(ZFileContent.getZFileConfig().getFilePath());
        Log.e(TAG, "initPathRecyclerView: " + zFilePathBeans.toString());
    }

    final List<ZFilePathBean> zFilePathBeans = new ArrayList<>();//存储遍历生成的数据

    /**
     * 递归
     * 传递一个基础路径后，通过file.getParent()构造出前面的所有文件（直到根目录为止），翻转后添加到路径列表适配器当中
     *
     * @param parentPath 递归文件绝对路径
     */
    private void reservedFile(String parentPath) {
        //构造出一个文件
        File file = new File(parentPath);
        //判断是否根目录
        if (TextUtils.isEmpty(file.getAbsolutePath()) || ZFileContent.getSD_ROOT().equals(file.getAbsolutePath())) {
            //将根目录添加
            zFilePathBeans.add(ZFileContent.toPathBean(new File(rootPath)));
            //如果仅有一个数据就不进行反转
            if (zFilePathBeans.size() != 1) {
                Collections.reverse(zFilePathBeans);
            }
            //设置数据
            filePathAdapter.setDatas(zFilePathBeans);
            //设置当前路径
            nowPath = zFilePathBeans.get(zFilePathBeans.size() - 1).getFilePath();
        } else {
            //非根目录 直接添加此目录
            zFilePathBeans.add(ZFileContent.toPathBean(file));
            //使用父路径继续递归
            reservedFile(file.getParent());
        }
    }

    private void initListRecyclerView() {
        fileListAdapter = new ZFileListAdapter(getContext());
        fileListAdapter.setItemClickByAnim(new ZFileListAdapter.ItemClickByAnim() {
            @Override
            public void onClick(View view, int position, ZFileBean bean) {
                if (bean.isFile()) {//isFile
                    if (fileListAdapter.isSelectModel()) {//isSelectModel
                        //selectModel add data
                        fileListAdapter.getSelectData().add(bean);
                        //change view
                        fileListAdapter.notifyDataSetChanged();
                    } else {//want to open this file
                        //open file
                        ZFileUtil.openFile(bean.getFilePath(), view);
                    }
                } else {//isDir
                    //path list add this item
                    filePathAdapter.addItemLast(ZFileContent.toPathBean(bean));
                    //reset this view
                    getData(bean.getFilePath());
                    //change now path
                    nowPath = bean.getFilePath();
                }
            }
        });
        fileListAdapter.setOnLongClickListener(new ZFileAdapter.OnLongClickListener<ZFileBean>() {
            @Override
            public boolean onLongClick(View view, int position, ZFileBean data) {

                if (data.isFile()) {
                    //进入选择模式
                    if (!fileListAdapter.isSelectModel()) {
                        //长安开启选择模式
                        fileListAdapter.setSelectModel(true);
                        fileListAdapter.reset();
                        fileListAdapter.getSelectData().add(data);

                        fileListAdapter.notifyDataSetChanged();

                        modifyLl.setVisibility(View.VISIBLE);
                        ((MainActivity) getActivity()).setSelectModelToolbar(true);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });
        fileListAdapter.setChangeListener(new ZFileListAdapter.ChangeListener() {
            @Override
            public void change(boolean isManage, int size) {
                if (isManage) {
                    if (barShow) {
                        //zfileListToolBar.setTitle(String.format("已选中%d个文件", size));
                    } else {
                        barShow = true;
                        //zfileListToolBar.setTitle("已选中0个文件");
                        //setMenuState();
                    }
                }
            }
        });
        fileListAdapter.setManage(ZFileContent.getZFileConfig().isManage());
        zfileListListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        zfileListListRecyclerView.setAdapter(fileListAdapter);


        getData(ZFileContent.getZFileConfig().getFilePath());
    }


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        callback = new OnBackPressedCallback(
                true // default to enabled
        ) {
            @Override
            public void handleOnBackPressed() {
                onBackPressed();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(
                this, callback);
    }

    public void onBackPressed() {
        Log.e(TAG, "fragment onbackpressed...");
        if (callback != null) {
            //select model
            if (fileListAdapter.isSelectModel()) {
                fileListAdapter.setSelectModel(false);
                fileListAdapter.reset();
                fileListAdapter.notifyDataSetChanged();
                modifyLl.setVisibility(View.GONE);
                ((MainActivity) getActivity()).setSelectModelToolbar(false);
                return;
            }

            //get path adapter now last path
            String path = filePathAdapter.getDatas().get(filePathAdapter.getDatas().size() - 1).getFilePath();
            //if path is root
            if (TextUtils.isEmpty(path) || (path != null && path.equals(rootPath))) { // 根目录
                //back to ClearFragment
                callback.setEnabled(false);//不响应返回事件
                callback.remove();
                //callback.remove();
                //将返回事件返回回去
                requireActivity().getOnBackPressedDispatcher().onBackPressed();
            } else { // 返回上一级
                // 先清除当前一级的数据
                filePathAdapter.removeLast();
                //get now last path
                String lastPath = filePathAdapter.getDatas().get(filePathAdapter.getDatas().size() - 1).getFilePath();
                // if the path is root
                if (TextUtils.isEmpty(lastPath) || "root".equals(lastPath) || ZFileContent.getSD_ROOT().equals(lastPath)) {
                    //get root path data
                    getData(ZFileContent.getSD_ROOT());
                } else {
                    getData(lastPath);
                }

                nowPath = lastPath;

                Log.e("backpress::", filePathAdapter.getDatas().toString());

                if (rootPath.equals(nowPath)) {

                } else {

                }
            }
        }
    }

    private void getData(String filePath) {
        //start refreshing
        zfileListRefreshLayout.setRefreshing(true);
        //load path
        ZFileContent.getZFileConfig().setFilePath(filePath);

        zfileListPathRecyclerView.scrollToPosition(filePathAdapter.getItemCount() - 1);

        ZFileUtil.getList(getContext(), list -> {
            if (list == null || list.size() == 0) {
                fileListAdapter.clear();
                zfileListEmptyLayout.setVisibility(View.VISIBLE);
            } else {
                fileListAdapter.setDatas(list);
                zfileListListRecyclerView.scrollToPosition(0);
                zfileListEmptyLayout.setVisibility(View.GONE);
            }
            zfileListRefreshLayout.setRefreshing(false);
        });

        nowPath = filePath;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rename_tv:
                DialogManager.renameDialog(getActivity()
                        , fileListAdapter.getSelectData().get(0).getFilePath()
                        , fileListAdapter.getSelectData().get(0).getFileName()
                        , new DialogManager.OnRenameListener() {
                            @Override
                            public void onSuccess(String newName, String newPath) {
                                updateSelectModelUI(false);
                                //更新数据
                                getData(nowPath);
                                showToast("rename success");
                            }

                            @Override
                            public void onFailed() {
                                showToast("rename failure");
                            }
                        });
                break;
            case R.id.delete_tv:
                DialogManager.deleteFileDialog(getActivity(), new DialogManager.OnDialogClickListener() {
                    @Override
                    public void onOKClick(Object data) {
                        //即将删除的文件路径
                        List<String> deleteFilePaths = new ArrayList<>();
                        //需要adapter更新的item位置
                        final Set<Integer> positions = new HashSet<>();

                        //遍历选中的数据
                        for (ZFileBean fileBean : fileListAdapter.getSelectData()) {
                            //拿到当前数据的路径
                            final String beanPath = fileBean.getFilePath();
                            //删除此文件
                            if (FileUtils.deleteFile(beanPath)) {
                                deleteFilePaths.add(beanPath);
                            }
                        }
                        showToast("delete success for " + deleteFilePaths.size() + " file");
                        //通知数据库更新已经删除的路径文件
                        ((BaseActivity) getActivity()).notifyFileIsDeleted(deleteFilePaths);

                        ((MainActivity) getActivity()).setSelectModelToolbar(true);
                        getData(nowPath);
                    }
                });

                break;
        }
    }

    @Override
    public void updateSelectModelUI(boolean isSelect) {
        if (isSelect) {
            modifyLl.setVisibility(View.VISIBLE);
        } else {
            modifyLl.setVisibility(View.GONE);
        }
        fileListAdapter.setSelectModel(isSelect);
    }

    @Override
    public boolean getModel() {
        return fileListAdapter.isSelectModel();
    }
}
